package org.renhj.register;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.renhj.config.ZookeeperConfig;

import java.util.Objects;

public class ZookeeperRegister extends Register{

    // 正常应该从环境变量或者配置文件里获取
//    private final static String ZOOKEEPER_HOST="192.168.2.101";
    private final static String ZOOKEEPER_HOST= ZookeeperConfig.ZOOKEEPER_HOST;
    private final static int ZOOKEEPER_PORT=ZookeeperConfig.ZOOKEEPER_PORT;
    private final static String PROVIDER_PATH=ZookeeperConfig.PROVIDER_PATH;
    private final static String CONSUMER_PATH=ZookeeperConfig.CONSUMER_PATH;
    private final static String PATH_SEPARATOR=ZookeeperConfig.PATH_SEPARATOR;

    private static final ZookeeperRegister zookeeperRegister = null;
    private final CuratorFramework curatorFramework;

    // 单例
    private ZookeeperRegister(String host, int port) {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(5000, 3);
        curatorFramework = CuratorFrameworkFactory.builder()
                .retryPolicy(retryPolicy)
                .connectionTimeoutMs(5000)
                .connectString(host + ":" + port)
                .namespace("curator")
                .build();
        curatorFramework.start();
    }

    public static ZookeeperRegister getInstance() {
        synchronized (ZookeeperRegister.class) {
            return Objects.requireNonNullElseGet(zookeeperRegister, () -> new ZookeeperRegister(ZOOKEEPER_HOST, ZOOKEEPER_PORT));
        }
    }

    @Override
    public void register(String service, String address) throws Exception {
        // 1、创建持久节点 /provider/UserService
        String servicePath = this.pathJoin(PROVIDER_PATH, service);
        Stat stat = curatorFramework.checkExists().forPath(servicePath);
        if (stat == null) {
            curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(servicePath);
        }

        // 2、创建临时节点，将ip地址作为path，根据zk特点，临时节点会自动删除
        // /provider/UserService/192.168.0.1:9000 /provider/UserService/192.168.0.1:9100
        curatorFramework.create().withMode(CreateMode.EPHEMERAL).forPath(pathJoin(PROVIDER_PATH, service, address));
    }



    public void release(String service, String address) throws Exception {
        System.out.println("删除zookeeper地址: " + pathJoin(PROVIDER_PATH, service, address));
        curatorFramework.delete().forPath(pathJoin(PROVIDER_PATH, service, address));
    }
























}
